package com.dolphin.aiagentplatform.ai.client;

import com.dolphin.aiagentplatform.ai.constant.AgentTypeConst;
import com.dolphin.aiagentplatform.ai.constant.ModelTypeConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Flux;

import static com.dolphin.aiagentplatform.ai.constant.AgentTypeConst.CHAT;

@Configuration
@Slf4j
public class DeepSeekR1ClientGenerator extends AbstractChatClientGenerator {

    @Value("${dolphin.ai.deepseek-r1.base-url}")
    private String baseUrl;

    @Value("${dolphin.ai.deepseek-r1.api-key}")
    private String apiKey;

    @Value("${dolphin.ai.deepseek-r1.model-name}")
    private String modelName;

    @Override
    protected String getBaseUrl() {
        return baseUrl;
    }

    @Override
    protected String getApiKey() {
        return apiKey;
    }

    @Override
    protected String getModelName() {
        return modelName;
    }

    @Override
    public AgentTypeConst getChatType() {
        return CHAT;
    }

    @Override
    public ModelTypeConst getModelType() {
        return ModelTypeConst.DEEPSEEK_R1;
    }
    
    /**
     * 重写chat方法，为DeepSeek-r1模型提供特殊处理
     * DeepSeek-r1模型不支持多轮对话的记忆功能，每次调用都需要只发送当前请求
     */
    @Override
    public Flux<String> chat(String systemPrompt, String userPrompt,
                           Double temperature, Integer maxTokens, String chatId) {
        log.debug("DeepSeek-r1模型特殊处理，禁用对话记忆: chatId={}", chatId);
        
        // 为DeepSeek-r1创建不带记忆功能的客户端
        ChatClient client = generateClientWithoutMemory(temperature, maxTokens);
        inMemoryChatIdRepository.save(getChatType().toString(), chatId);

        // 创建提示构建器
        var promptBuilder = client.prompt();

        // 只有当systemPrompt有内容时才添加system消息
        if (StringUtils.hasText(systemPrompt)) {
            promptBuilder.system(systemPrompt);
        }

        // 添加用户消息并返回流，不使用记忆功能
        return promptBuilder
                .user(userPrompt)
                .stream()
                .content();
    }
    
    /**
     * 生成不带记忆功能的ChatClient
     * 仅使用SimpleLoggerAdvisor，不添加MessageChatMemoryAdvisor
     */
    protected ChatClient generateClientWithoutMemory(Double temperature, Integer maxTokens) {
        OpenAiApi api = new OpenAiApi(getBaseUrl(), getApiKey());
        OpenAiChatOptions options = OpenAiChatOptions.builder()
                .temperature(temperature)
                .maxTokens(maxTokens)
                .model(getModelName())
                .build();
        OpenAiChatModel openAiChatModel = new OpenAiChatModel(api, options);
        
        return ChatClient.builder(openAiChatModel)
                .defaultOptions(options)
                .defaultAdvisors(new SimpleLoggerAdvisor()) // 只使用日志记录器，不使用聊天记忆
                .build();
    }
}
